package cn.gwm.utils;

import cn.gwm.flink.streaming.constant.DefaultConstant;
import cn.gwm.flink.streaming.task.BaseTask;
import org.apache.flink.api.java.utils.ParameterTool;

import java.io.IOException;
import java.util.Properties;

/**
 * 读取配置文件的工具类
 */
public class ConfigLoader {

    public static ParameterTool parameterTool = null;
    public static Properties props = null;

    static {
        try {
            parameterTool = ConfigLoader.initConfig();
            props = parameterTool.getProperties();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void init(String[] args) {
        parameterTool = ParameterTool.fromArgs(args);
        parameterTool.getProperties().forEach((k, v) -> {
            props.setProperty((String) k, (String) v);
        });
    }

    public static ParameterTool initConfig() throws IOException {
        String suffix = System.getenv().get(DefaultConstant.BOOT_PROFILES_ACTIVE);
        if (suffix == null) {
            suffix = "dev";
        }
        System.out.println("suffix:" + suffix);
        ParameterTool parameterTool = ParameterTool.fromPropertiesFile(
                BaseTask.class.getClassLoader().getResourceAsStream("conf-" + suffix + ".properties"));
        return parameterTool;
    }

    /**
     * 编写方法获取配置项的key对应的值
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        return props.getProperty(key);
    }

    public static String get(String key, String val) {
        return props.getProperty(key, val);
    }

    /**
     * 编写方法获取int的key值
     *
     * @param key
     * @return
     */
    public static Integer getInt(String key) {
        return Integer.parseInt(props.getProperty(key));
    }

    public static Long getLong(String key) {
        return Long.parseLong(props.getProperty(key));
    }

    public static Boolean getBoolean(String key) {
        return Boolean.parseBoolean(props.getProperty(key));
    }

    public static Double getDouble(String key) {
        return Double.parseDouble(props.getProperty(key));
    }
}
